// chrome.storage.sync.get('color', ({
// 		color
// 	}) => {
// 		//alert(color)
// 		// content.js
// 		chrome.runtime.sendMessage("test", r => {
// 			alert(r)
// 		});
// 	});


GoTo()


document.addEventListener('DOMContentLoaded', async () => {


	if (localStorage.getItem('cacheselectHtml')) {
		document.querySelector('#boxSet').innerHTML = localStorage.getItem('cacheselectHtml')
	}
	if (localStorage.getItem('cachemyfontsize')) {
		let cachemyfontsize = localStorage.getItem('cachemyfontsize')
		document.querySelector("#myfontsize").value = cachemyfontsize
		document.querySelector("#myfontsizeValue").innerText = cachemyfontsize == 0 ? '默认' : cachemyfontsize

	}



	let cacheselectValues = JSON.parse(localStorage.getItem('cacheselectValue'))
	const selectElements = document.querySelectorAll('.select');
	try {
		for (let i = 0; i < selectElements.length; i++) {

			selectElements[i].querySelector('textarea').value = cacheselectValues[i].keyword;
			selectElements[i].querySelector('.forecolor').value = cacheselectValues[i].foreColor;
			selectElements[i].querySelector('.bgccolor').value = cacheselectValues[i].bgcColor;
		}
	} catch (e) {
		//TODO handle the exception
	}


	/* const btn_execute = document.getElementById('btn-execute');
	let keywords = document.getElementById('keywords'); */


	document.querySelector('#addNew').onclick = function() {

		SelectRender()
		localStorage.setItem('cacheselectHtml', document.querySelector('#boxSet').innerHTML)
	}




	function SelectRender() {

		let div = document.createElement('div');
		div.className = 'select'
		div.innerHTML = `
		    <div style="margin-top: 5px;width: 100%;">
		    	<textarea style="max-width: 98%;min-width: 98%;width: 98%;font-size: 12px;height: 48px;"
		    		placeholder="类别关键字使用英文逗号分割如 a,b,c" class="keywords"></textarea>
		    </div>
		    <div style="display: flex;align-items: center;margin-top: 5px;width: 100%;">
		    	<span style="font-size: 12px;">字体颜色</span><input style="margin-left: 5px;" value="#e43525"
		    		type="color" class="forecolor" name="" id="">
		    	<span style="margin-left: 15px;font-size: 12px;">背景颜色</span><input value="#fcff2d"
		    		style="margin-left: 5px;" type="color" class="bgccolor" name="" id="">
		    	<button class="remove"
		    		style="background-color: #909399; width: 50px;height: 22px;border: 0;border-radius: 6px;color: #fff;font-size: 12px;margin-left: 16px;">删除</button>
		    </div>
		    <hr style="width: 100%;">
		  `;
		document.querySelector('#boxSet').appendChild(div);
	}


	const myfontsize = document.querySelector("#myfontsize");

	myfontsize.addEventListener("input", function() {
		document.querySelector("#myfontsizeValue").innerText = this.value == 0 ? '默认' : this.value +
			'px'
	});


	document.querySelector('#boxSet').addEventListener('click', function(event) {
		if (event.target.classList.contains('remove')) {
			// 处理相应的逻辑
			event.target.parentNode.parentNode.remove();
			localStorage.setItem('cacheselectHtml', document.querySelector('#boxSet').innerHTML)
		}
	});

	document.querySelector('#boxSet').addEventListener('input', function(event) {
		if (event.target.classList.contains('keywords')) {
			// 处理相应的逻辑
			CacheHtml(false);
		}
	});
	document.querySelector('#boxSet').addEventListener('input', function(event) {
		if (event.target.classList.contains('forecolor')) {
			CacheHtml(false);
		} else if (event.target.classList.contains('bgccolor')) {
			CacheHtml(false);
		}
	});


	document.querySelector('#save').onclick = async () => {

		let groupKeyWords = CacheHtml(true)
		chrome.storage.sync.set({
			groupKeyWords
		});



		const [tab] = await chrome.tabs.query({
			active: true,
			currentWindow: true
		});
		await chrome.scripting.executeScript({
			target: {
				tabId: tab.id
			},
			func: RRR
			//args: [keywords_arr]
		});

	}


	chrome.storage.sync.get('IsOpen', ({
		IsOpen
	}) => {
		if (!IsOpen) {
			document.querySelector('#openOrclose').checked = true;
		} else {
			document.querySelector('#openOrclose').checked = false;
		}
	})


	let openOrclose = document.querySelector('#openOrclose')
	openOrclose.addEventListener('change', async () => {

		await chrome.runtime.sendMessage("ExecuteIsOpen", async r => {

			const [tab] = await chrome.tabs.query({
				active: true,
				currentWindow: true
			});
			await chrome.scripting.executeScript({
				target: {
					tabId: tab.id
				},
				func: RRR,
				//args: [keywords_arr]
			});
		});
	});


	// 判断字符串是否包含中文逗号
	function hasChineseComma(str) {
		// 匹配中文字符或者逗号
		const reg = /[\u4e00-\u9fa5，]/;
		return reg.test(str);
	}


	function CacheHtml(flag) {
		let groupKeyWords = []
		const selectElements = document.querySelectorAll('.select');
		for (let i = 0; i < selectElements.length; i++) {
			const textareaValue = selectElements[i].querySelector('textarea').value;
			if (textareaValue == '' && flag) {
				alert('保存失败，关键字不能为空')
				return
			}
			if (textareaValue.indexOf('，') !== -1 && flag) {

				alert('保存失败，请输入英文逗号[,]')
				return
			}
			const bgcColor = selectElements[i].querySelector('.bgccolor').value;
			const foreColor = selectElements[i].querySelector('.forecolor').value;
			const myfontsize = document.querySelector('#myfontsize').value
			// 对获取到的 textareaValue 和 inputColor 进行处理
			groupKeyWords.push({
				keyword: textareaValue,
				foreColor: foreColor,
				bgcColor: bgcColor,
				myfontsize: myfontsize
			})
		}
		localStorage.setItem('cacheselectValue', JSON.stringify(groupKeyWords))
		localStorage.setItem('cachemyfontsize', document.querySelector("#myfontsize").value)
		return groupKeyWords
	}

});



function RRR() {
	location.reload()
}




function GoTo() {


	chrome.storage.sync.get('groupKeyWords', ({
		groupKeyWords
	}) => {



		chrome.storage.sync.get('IsOpen', ({
			IsOpen
		}) => {
			if (!IsOpen) {

				function Live2d(l_json) {
					try {
						L2Dwidget.init({
							"model": {
								"jsonPath": l_json,
								"scale": 1,
								"hHeadPos": 0.5,
								"vHeadPos": 0.618,
							},
							"display": {
								"position": "left",
								"width": 100,
								"height": 100,
								"hOffset": 0,
								"vOffset": 0
							},
							"mobile": {
								"show": true,
								"scale": 0.5
							},
							"react": {
								"opacityDefault": 0.7,
								"opacityOnHover": 0.2
							}
						});

					} catch (e) {
						//TODO handle the exception
					}
				}



				var now = new Date();
				var hour = now.getHours();

				if (hour <= 12) {
					Live2d(
						'https://unpkg.com/live2d-widget-model-tororo@1.0.5/assets/tororo.model.json'
					)
				} else {
					Live2d(
						'https://unpkg.com/live2d-widget-model-hijiki@1.0.5/assets/hijiki.model.json'
					)
				}

				let objarr = []
				const myMap = new Map();
				let mylength = 0

				try {
					setInterval(() => {

						if (mylength != document.querySelectorAll('*').length) {
							console.log('mylength', mylength);
							mylength = document.querySelectorAll('*').length
							const element = document.querySelector('.kka');
							element.innerHTML = ''
							objarr = []


							if (groupKeyWords) {

								groupKeyWords.forEach(r => {
									let keywords_arr = r.keyword.split(",");
									let forecolor = r.foreColor
									let bgccolor = r.bgcColor
									let myfontsize = r.myfontsize
									Render(keywords_arr, forecolor, bgccolor,
										myfontsize)
								})
							}
						}

					}, 1000)

				} catch (e) {
					//TODO handle the exception
				}


				var toptit = document.createElement('div');
				//toptit.style.backgroundColor = '#d3d3d3';
				toptit.style.marginRight = '20px'
				toptit.style.color = 'red';
				//toptit.style.display = 'none'
				toptit.style.position = 'fixed'
				toptit.style.left = '8px'
				toptit.style.top = '6px'
				toptit.style.padding = '8px 0';
				toptit.style.borderRadius = '6px'
				toptit.style.display = 'flex';
				toptit.style.alignItems = 'center'
				toptit.style.flexWrap = 'wrap'
				toptit.style.backgroundColor = 'rgba(0, 0, 0, 0.5)'
				toptit.style.zIndex = 999999
				toptit.className = 'kka'
				document.body.prepend(toptit)
				toptit.addEventListener('mouseenter', () => {

					const elements = document.querySelectorAll('.words');
					for (let i = 0; i < elements.length; i++) {
						elements[i].style.cursor = 'pointer';
						elements[i].style.userSelect = 'none';
					}
				});

				toptit.addEventListener('mouseleave', () => {

				});


				var isDragging = false;
				//定位移动
				toptit.addEventListener("mousedown", function(e) {
					isDragging = true;
					var startX = e.clientX - toptit.offsetLeft;
					var startY = e.clientY - toptit.offsetTop;

					function moveHandler(e) {
						if (isDragging) {
							toptit.style.left = e.clientX - startX + "px";
							toptit.style.top = e.clientY - startY + "px";
						}
					}

					function upHandler(e) {
						isDragging = false;
						document.removeEventListener("mousemove", moveHandler);
						document.removeEventListener("mouseup", upHandler);
					}

					document.addEventListener("mousemove", moveHandler);
					document.addEventListener("mouseup", upHandler);
				});



				function scrollWord(text, wordnum, thishtml, bgccolor, myfontsize) {

					let scrollTops = domdistinct().filter(r => r.keyword.includes(text) && r.element
						.className ==
						'word_ddl' && r.element.offsetHeight > 0)

					scrollTops.sort(function(a, b) {
						return a.scrollTop - b.scrollTop;
					});

					//console.log('scrollTops', scrollTops);

					// if (myMap.get(text) == 1) {
					// 	console.log(bgccolor);
					// 	console.log(myfontsize);
					// 	scrollTops.forEach(r=>{
					// 		console.log(r);
					// 		r.element.style.backgroundColor = bgccolor
					// 		if(myfontsize == 0)
					// 		{
					// 			const defaultStyles = window.getComputedStyle(r.element);
					// 			r.element.style.fontSize = defaultStyles.fontSize;
					// 		}
					// 		else
					// 		{
					// 			r.element.style.fontSize = myfontsize
					// 		}

					// 	})
					// }

					if (!myMap.has(text)) {
						myMap.set(text, 0)
					} else {
						let num = parseInt(myMap.get(text)) + 1
						myMap.set(text, num)
					}
					let wordindex = parseInt(myMap.get(text))

					let index = thishtml.innerText.indexOf('-');
					let oldresult = thishtml.innerText
					if (index != -1) {
						oldresult = thishtml.innerText.substring(0, index).trim();
					}
					let newthishtml = oldresult + '- 第' + parseInt(wordindex + 1) + '个'
					thishtml.innerHTML = newthishtml

					if (wordindex >= wordnum) {

						thishtml.innerHTML = thishtml.innerText.split('-')[0] + '- 第1个'
						myMap.set(text, 0)
						wordindex = 0
					}


					if (scrollTops.length > wordindex) {

						// console.log('wordindex', wordindex);
						//console.log('objarr', objarr);
						console.log('scrollTops', scrollTops);
						const elementHeight = scrollTops[wordindex].element.offsetHeight;
						const windowHeight = window.innerHeight;
						const scrollDistance = scrollTops[wordindex].element.offsetTop - (windowHeight -
							elementHeight) / 2;
						window.scrollTo({
							top: scrollTops[wordindex].scrollTop, //element.offsetTop,
							behavior: 'smooth'
						});

						scrollTops[wordindex].element.style.backgroundColor = '#f7993d'
						scrollTops[wordindex].element.style.fontWeight = '800'

						if (scrollTops.length == 1) {
							myMap.set(text, 0)
							wordindex = 0
						}
					} else {
						wordindex = 0
					}
				}


				function domdistinct() {

					let uniqueArr = objarr.reduce((acc, current) => {
						const x = acc.find(item => item.scrollTop === current.scrollTop && item
							.keyword ===
							current.keyword && item.offsetLeft === current.offsetLeft);
						if (!x) {
							return acc.concat([current]);
						} else {
							return acc;
						}
					}, []);
					uniqueArr = uniqueArr.filter(r => r.scrollTop != -1)
					return uniqueArr
				}


				function findBottomElementWithKeyword(node, keyword, forecolor, bgccolor, myfontsize) {


					//当是文本节点，无标签时候，返回父节点
					if (node.nodeType === Node.TEXT_NODE && node.textContent.includes(keyword)) {
						return node.parentNode;
					}

					if (node.nodeType !== Node.ELEMENT_NODE) {
						return null;
					}


					let flag = 0
					if (node.textContent.includes(keyword)) {

						flag = 1
						let bottomElement = null;

						//for (let i = 0; i < node.children.length; i++) {
						for (let i = 0; i < node.childNodes.length; i++) {

							//const child = node.children[i];
							const child = node.childNodes[i];
							if (child.tagName === "SCRIPT") {
								continue;
							}


							const bottomChild = findBottomElementWithKeyword(child, keyword, forecolor,
								bgccolor,
								myfontsize);
							if (bottomChild) {

								flag = 0
								bottomElement = bottomChild;

								//var scrollTop = bottomElement.offsetTop; // 获取元素距离顶部的距离(父子相对定位会影响)
								const rect = bottomElement.getBoundingClientRect();
								const scrollTop = rect.top + window.scrollY;

								//const offsetLeft = bottomElement.offsetLeft
								const rectleft = rect.left
								if (!objarr.some(r => r.element == bottomElement)) {
									objarr.push({
										element: bottomElement,
										scrollTop: scrollTop - 100,
										offsetLeft: rectleft,
										keyword: keyword
									})
								}
							}
						}
						if (flag != 0 && bottomElement == null) {
							let regex = new RegExp(keyword, 'g');
							let thishtml2 =
								`<span class="word_ddl" style="background-color: ${bgccolor};color: ${forecolor};font-size: ${myfontsize}px">${keyword}</span>`;
							if (myfontsize == 0) {
								thishtml2 =
									`<span class="word_ddl" style="background-color: ${bgccolor};color: ${forecolor};">${keyword}</span>`;
							}

							if (!node.parentNode.classList.contains('word_ddl')) {
								if (!node.classList.contains('word_ddl')) {
									var html22 = node.innerHTML.replace(regex, thishtml2);
									node.innerHTML = html22
								}
							}
						}
						return bottomElement || node;
					}
					return null;
				}


				function HtmlReplace(keyword, forecolor, bgccolor, myfontsize) {

					try {
						let regex = new RegExp(keyword, 'g');
						let thishtml2 =
							`<span class="word_ddl" style="background-color: ${bgccolor};color: ${forecolor};font-size: ${myfontsize}px;">${keyword}</span>`;
						if (myfontsize == 0) {
							thishtml2 =
								`<span class="word_ddl" style="background-color: ${bgccolor};color: ${forecolor};">${keyword}</span>`;
						}

						objarr.forEach(thishtml => {

							if (thishtml.element.textContent.includes(keyword)) {

								if (!thishtml.element.parentNode.classList.contains(
										'word_ddl')) {
									if (!thishtml.element.classList.contains('word_ddl')) {

										var html22 = thishtml.element.innerHTML.replace(regex,
											thishtml2);
										thishtml.element.innerHTML = html22
									}
								}
							}
						});
					} catch (e) {
						//TODO handle the exception
					}
				}







				function ElementCount(keywords) {

					let str = ''
					var basedoms = GetIframeDom()
					basedoms.push(document.body)

					basedoms.forEach(dombody => {
						keywords.forEach(keyword => {

							const regex = new RegExp(keyword, 'gi');
							//let text = dombody.innerHTML;
							let text = dombody.innerText;
							// text = text.replace(/<script[\s\S]*?<\/script>/gi,
							// 	''); // 排除 <script> 标签中的内容
							// text = text.replace(/<[^>]+class="words"[^>]*>[\s\S]*?<\/[^>]+>/gi,
							// 	''); // 排除 class 为words的元素

							const matches = text.match(regex);
							if (matches && matches.length > 0) {
								str += `${keyword} : 【${matches.length}】,`
							}
						});
					});
					str = str.substring(0, str.length - 1)
					return str
				}



				function GetIframeDom() {
					var domarr = []
					try {
						var iframes = document.getElementsByTagName('iframe');
						for (var i = 0; i < iframes.length; i++) {
							var iframeDoc = iframes[i].contentDocument || iframes[i].contentWindow
								.document;
							domarr.push(iframeDoc.body)
						}
					} catch (e) {
						//TODO handle the exception
					}

					return domarr
				}



				function Render(keywords, forecolor, bgccolor, myfontsize) {
					var basedoms = GetIframeDom()
					basedoms.push(document.body)
					basedoms.forEach(dombody => {
						keywords.forEach(keyword => {
							const bottomElement = findBottomElementWithKeyword(dombody,
								keyword,
								forecolor, bgccolor, myfontsize);
							if (bottomElement) {
								HtmlReplace(keyword, forecolor, bgccolor, myfontsize)
							}
						});
					});

					var str = ElementCount(keywords)

					const element = document.querySelector('.kka');
					if (str != null && str != '') {
						let words = str.split(',')
						element.style.display = 'inline-block'
						words.forEach(r => {
							if (!element.textContent.includes(r)) {
								let thisword = r.split(':')
								var sightml = document.createElement('span');
								sightml.style.backgroundColor = bgccolor;
								sightml.style.marginLeft = '10px'
								sightml.style.marginRight = '10px'
								sightml.style.fontSize = '15px'
								sightml.style.borderRadius = '5px'
								sightml.style.padding = '2px 7px'
								sightml.style.color = forecolor;
								sightml.className = 'words'
								sightml.textContent = r
								sightml.onclick = function() {
									let wordnum = thisword[1].trim().replace(/【|】/g, '');
									scrollWord(thisword[0].trim(), parseInt(wordnum), this,
										bgccolor,
										myfontsize);
								}
								element.appendChild(sightml)
							}
						})
					} else {
						// element.style.display = 'none'
						// element.innerHTML = null
					}


				}

			}
		})
	});
}